﻿using System.ServiceModel;
using Aluetjen.EMailService.Contract;
using Aluetjen.EmailService.Domain.Services;
using Aluetjen.EmailService.Infrastructure;

namespace Aluetjen.EmailService.Agent
{
    [StructureMapServiceBehavior]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class EmailService : IEmailService
    {
        private readonly IPipelineProcessorService _processor;

        static EmailService()
        {
            AutoMapper.Mapper.CreateMap<MailMessage, Domain.Models.Message.MailMessage>().
                ForMember(x => x.Id, t => t.Ignore());
            AutoMapper.Mapper.CreateMap<MailAddress, Domain.Models.Message.MailAddress>().
                ForMember(x => x.Id, t => t.Ignore());
            AutoMapper.Mapper.CreateMap<Attachment, Domain.Models.Message.Attachment>().
                ForMember(x => x.Id, t => t.Ignore());

            AutoMapper.Mapper.AssertConfigurationIsValid();
        }

        public EmailService(IPipelineProcessorService processor)
        {
            _processor = processor;
        }

        [UnitOfWorkBehavior]
        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
        public void Send(MailMessage message)
        {
            var domainMessage = AutoMapper.Mapper.Map<MailMessage, Domain.Models.Message.MailMessage>(message);

            _processor.ProcessMessage(domainMessage);
        }
    }
}
